package cn.kgc.javaweb.servlet;

import cn.kgc.javaweb.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: mosin
 * @version: v1.0  2022/5/30
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");

        switch (method){
            case "login":
                login(req, resp);
                break;
            case "reg":
                reg(req, resp);
                break;
        }

    }

    //登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //System.out.println("登录请求被接收");
        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if("admin".equals(username)&&"888".equals(password)){
            //保存用户信息到session
            User user = User.builder().username(username).password(password).build();
            req.getSession().setAttribute("user",user);
            //跳转页面到主页
            resp.sendRedirect(req.getContextPath()+"/main.jsp"); //    /javaweb/login.jsp
        }else{ // 重定向到login.jsp

            resp.sendRedirect(req.getContextPath()+"/login.jsp");

        }



    }
    //注册
    protected void reg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("注册请求被接收");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username:"+username);
        System.out.println("password = " + password);
    }


}
